package cn.itcast.bos.service.user.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.user.UserDao;
import cn.itcast.bos.domain.auth.Role;
import cn.itcast.bos.domain.user.User;
import cn.itcast.bos.service.user.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	public void save(User user) {
		userDao.save(user);// 只能保存 用户信息 ...角色信息? 中间表数据 ...
	}

	public void deleteUser(User user) {
		userDao.delete(user);
	}

	public void updateUserPasswordByUsername(String name, String pwd) {
		userDao.updateUser(name, pwd);
	}

	public User findUserById(String id) {
		return userDao.findOne(id);
	}

	public List<User> findAllUsers() {
		return userDao.findAll();
	}

	public User findUserByUsernameAndPassword(String username, String password) {
		// 用户自定义查询 添加条件 在UserDao 提供一个方法即可 ..
		// return userDao.findByUsernameAndPassword(username, password);// 登陆查询
		// return userDao.login(username, password);// 登陆查询
		// return userDao.login1(username, password);// 登陆查询
		return userDao.mylogin3(username, password);// 登陆查询
	}

	public User findUserByUsername(String username) {
		return userDao.findUserByUsername(username);
	}

	public void save(User model, String[] roleIds) {
		userDao.saveAndFlush(model);// model 瞬时态 uuid
		if (roleIds != null && roleIds.length != 0) {
			// 添加用户选择角色 user_role
			for (String id : roleIds) {
				Role r = new Role();
				r.setId(id);// 托管态 用户级联 删除 user_id role_id
				model.getRoles().add(r);
			}
		}

	}

	public Page<User> findAll(Pageable pageRequest) {
		return userDao.findAll(pageRequest);
	}

}
